package cn.juni.service.impl;

import cn.juni.dao.IUserInfoDao;
import cn.juni.pojo.Role;
import cn.juni.pojo.UserInfo;
import cn.juni.service.IUserInfoService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author Juni
 * @date 2021/2/25
 */
@Service("userService")
public class UserInfoServiceImpl implements IUserInfoService {

    @Autowired
    IUserInfoDao userInfoDao;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    /**
     * 该方法的主要目的是从数据库中获取用户的信息，将信息包装到security提供的User对象中
     * 内部会自动对该User中的信息进行认证操作
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //获取指定用户名的信息
        UserInfo userInfo = userInfoDao.findUserInfoByName(username);
        //将该信息进行认证操作
        //参数一：用户名，参数二：密码，参数三：该用户的所具备的所有角色
        User user = new User(
                userInfo.getUsername(),
                userInfo.getPassword(),
                userInfo.getStatus()==0?false:true,
                true,true,true,
                getAuthority(userInfo.getRoles()));
        return user;
    }

    /**
     * 模拟用户权限：自己手动给用户指定的权限
     */
    public List<SimpleGrantedAuthority> getAuthority(List<Role> roleList){
        List<SimpleGrantedAuthority> list = new ArrayList<SimpleGrantedAuthority>();
        for(Role role : roleList){
            list.add(new SimpleGrantedAuthority("ROLE_"+role.getRoleName()));
        }
        return list;
    }

    public List<UserInfo> findAll(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        return userInfoDao.findAll();
    }

    public int insertUserInfo(UserInfo userInfo) {
        userInfo.setId(UUID.randomUUID().toString().replace("-",""));
        userInfo.setPassword(bCryptPasswordEncoder.encode(userInfo.getPassword()));
        return userInfoDao.insertUserInfo(userInfo);
    }

    public UserInfo findUserInfoById(String id) {
        return userInfoDao.findUserInfoById(id);
    }

    public List<Role> findOtherRole(String uid) {
        return userInfoDao.findOtherRole(uid);
    }

    public void insertUserRole(String userId, String[] ids) {
        for(String roleId : ids){
            userInfoDao.insertUserRole(userId,roleId);
        }
    }
}
